//
//  SearchViewController.m
//  喜马拉雅FM
//
//  Created by dllo on 16/3/3.
//  Copyright © 2016年 lanou.com. All rights reserved.
//

#import "SearchViewController.h"
#import "NetworkHandlerBlock.h"
#import "ModelForSearch.h"
#import "UIImageView+WebCache.h"
#import "SecendViewController.h"

@interface SearchViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *arrForSearch;

@property (nonatomic, retain) UISearchBar *search;
@property (nonatomic, retain) UIButton *backButton;

@property (nonatomic, retain) NSString *searchText;


@end

@implementation SearchViewController


- (void)dealloc {
    
    [_tableView release];
    [_arrForSearch release];
    [_search release];
    [_backButton release];
    [_searchText release];
    [super dealloc];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationItem.hidesBackButton = YES;
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    [self createSearchBar];
    [self createTableView];
}

- (void)createSearchBar {
    
    self.search = [[UISearchBar alloc]initWithFrame:CGRectMake(10, 0, [UIScreen mainScreen].bounds.size.width - 50-10, 44)];
    [self.navigationController.navigationBar addSubview:self.search];
    self.navigationController.navigationBar.backgroundColor = [UIColor grayColor];
    [self.search release];
    self.search.placeholder = @"搜索";
    
    self.search.layer.cornerRadius = 10;
    self.search.layer.masksToBounds = YES;
    
    self.search.delegate = self;
    
    
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.navigationController.navigationBar addSubview:self.backButton];
    self.backButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 50, 0, 50, 44);
    [self.backButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.backButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(handleButton:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)handleButton:(UIButton *)button {
    
    [self.navigationController popViewControllerAnimated:YES];
    self.search.hidden = YES;
    self.backButton.hidden = YES;
    
}

- (void)createTableView {
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 10, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView release];
    
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"poolForUITableViewCell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arrForSearch.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ModelForSearch *model = [self.arrForSearch objectAtIndex:indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForUITableViewCell"];
    
    
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.imgPath] placeholderImage:[UIImage imageNamed:@"2.jpg"]];
    
    cell.textLabel.text = model.keyword;
    
    // 关键字高亮.
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc]initWithString:cell.textLabel.text];
    
    NSStringCompareOptions mask = NSCaseInsensitiveSearch | NSNumericSearch;
    
    NSRange range = [cell.textLabel.text rangeOfString:self.searchText options:mask];
    
    
    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    
    
    [cell.textLabel setAttributedText:attri];
    
    [attri release];
 
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ModelForSearch *model = [self.arrForSearch objectAtIndex:indexPath.row];
    SecendViewController *secend = [[SecendViewController alloc]init];
    secend.stringForAlbumID = model.keyid;
    
    [self.navigationController pushViewController:secend animated:YES];
    
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    NSLog(@"%@",searchText);
    
    self.arrForSearch = [NSMutableArray array];
    
    NSString *tempString = [searchText stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    
   NSString *stringUrl = [NSString stringWithFormat:@"http://search.ximalaya.com/suggest?device=android&kw=%@",tempString];
    self.searchText = searchText;
   
   __block typeof(self)weakSelf = self;
    [NetworkHandlerBlock netWorkingWithURL:stringUrl completeHandle:^(NSURLResponse *response, NSData *data, id result) {
       
        NSArray *arrTemp = [result objectForKey:@"albumResultList"];
        for (NSDictionary *dic in arrTemp) {
           
            ModelForSearch *model = [[ModelForSearch alloc]init];
          
           [model setValuesForKeysWithDictionary:dic];
           
            // 当遇到数据源的key值是关键词的时候,改key值名,并在此处重新给这个key值赋上相应的Value值
            model.keyid =[dic objectForKey:@"id"];
            
            NSLog(@"----%@",model.keyid);
           
            [weakSelf.arrForSearch addObject:model];
          
            [model release];
       }
       
        [weakSelf.tableView reloadData];

    }];
}


- (void)viewWillDisappear:(BOOL)animated {
    
    // 键盘回收.
    [self.search endEditing:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}


@end
